package com.ttc.group2.videochat.database;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.ttc.group2.videochat.model.User;
import com.ttc.group2.videochat.utils.Const;

public class DbHelper {

	private final Context mContext;
	private static final String TAG = DbHelper.class.getSimpleName();
	private static final String DATABASE_NAME = "videochat.db";
	private static final int DATABASE_VERSION = 1;
	private static DbHelper instance;
	private SQLiteDatabase mDb;
	private DatabaseHelper mDbHelper;

	private static class DatabaseHelper extends SQLiteOpenHelper {

		public DatabaseHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			Tables.UserTable.setup(db);
			Tables.FriendTable.setup(db);
			Tables.MessageTable.setup(db);
			Tables.GroupTable.setup(db);
			Tables.RecentTable.setup(db);
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
					+ newVersion);
			// TO DO something here

		}

	}

	private DbHelper(Context context) {
		this.mContext = context;
	}

	public static synchronized DbHelper getInstance(Context context) {
		if (instance == null) {
			instance = new DbHelper(context);
			instance.open();
		}
		return instance;
	}

	public synchronized void open() {
		this.mDbHelper = new DatabaseHelper(mContext);
		mDb = this.mDbHelper.getWritableDatabase();
	}

	public synchronized void close() {
		mDbHelper.close();
	}

	/*
	 * ######################## CRUD with Database
	 * *####################################
	 */

	// insert single User
	public void insertUser(ContentValues values, User lUser) {
		mDb.insert(Tables.UserTable.TableName, null, values);
	}

	// Save list users
	public void saveUsers(List<User> users) {
		for (User lUser : users) {
			saveUser(lUser);
		}
	}

	// Save single User
	public void saveUser(User user) {
		ContentValues values = getContentValuesUser(user);
		String condition = String.format("%s = ?", Tables.UserTable.USER_ID);
		String[] whereArgs = { String.valueOf(user.getUserId()) };
		Cursor cursor = mDb.query(Tables.UserTable.TableName,
				Tables.UserTable.COLUMNS, condition, whereArgs, null, null,
				null);
		if (cursor != null && cursor.getCount() > Const.ZERO_INT_VALUE) {
			DbHelper.getInstance(mContext).updateUser(values, user);
		} else {
			DbHelper.getInstance(mContext).insertUser(values, user);
		}
		if (cursor != null) {
			cursor.close();
		}
	}

	private ContentValues getContentValuesUser(User user) {
		ContentValues values = new ContentValues();
		values.put(Tables.UserTable.USER_ID, user.getUserId());
		values.put(Tables.UserTable.FULL_NAME, user.getFullName());
		values.put(Tables.UserTable.EMAIL, user.getEmail());
		values.put(Tables.UserTable.IS_ONLINE, user.isOnline());
		return values;
	}

	// update User
	public void updateUser(ContentValues values, User lUser) {
		String selection = String.format("%s = ?", Tables.UserTable.USER_ID);
		String[] selectionArgs = { String.valueOf(lUser.getUserId()) };
		mDb.update(Tables.UserTable.TableName, values, selection, selectionArgs);
	}

	// get User detail
	public User getUserCursor(Cursor cursor) {
		User lUser = new User();
		int user_idIndex = cursor.getColumnIndex(Tables.UserTable.USER_ID);
		int full_nameIndex = cursor.getColumnIndex(Tables.UserTable.FULL_NAME);
		int emailIndex = cursor.getColumnIndex(Tables.UserTable.EMAIL);
		int is_OnlineIndex = cursor.getColumnIndex(Tables.UserTable.IS_ONLINE);

		int user_id = cursor.getInt(user_idIndex);
		String fullName = cursor.getString(full_nameIndex);
		String email = cursor.getString(emailIndex);
		long isOnline = cursor.getInt(is_OnlineIndex);

		lUser.setUserId(user_id);
		lUser.setFullName(fullName);
		lUser.setEmail(email);
		lUser.setOnline(isOnline > 0);

		return lUser;
	}

	public User getUserById(int user_id) {
		String selection = String.format("%s = ?", Tables.UserTable.USER_ID);
		String[] selectionArgs = { String.valueOf(user_id) };
		Cursor cursor = mDb.query(Tables.UserTable.TableName,
				Tables.UserTable.COLUMNS, selection, selectionArgs, null, null,
				null);
		User user = null;
		try {
			if (cursor != null && cursor.moveToFirst()) {
				do {
					user = getUserCursor(cursor);
				} while (cursor.moveToNext());
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			if (cursor != null) {
				cursor.close();
			}
		}

		return user;
	}

	// Delete User
	public void deleteUser(int user_id) {
		String whereClause = String.format("%s = ?", Tables.UserTable.USER_ID);
		String[] whereArgs = { String.valueOf(user_id) };
		mDb.delete(Tables.UserTable.TableName, whereClause, whereArgs);
	}

	// Get list User
	public List<User> getListUsers() {
		List<User> users = new ArrayList<User>();
		Cursor c = mDb.query(Tables.UserTable.TableName,
				Tables.UserTable.COLUMNS, null, null, null, null, null);
		try {
			if (c != null && c.moveToFirst()) {
				do {
					User user = getUserCursor(c);
					users.add(user);
				} while (c.moveToNext());
			}
		} catch (Exception e) {

		} finally {
			if (c != null) {
				c.close();
			}
		}
		return users;
	}

}
